package com.bestom.t9mod.base.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import com.bestom.t9mod.commons.utils.DataTurn;
import com.bestom.t9mod.core.api.PowerApi;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android_serialport_api.SerialPort;

public class SerialPortService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("SerialPortService","SerialPortService onBind");
        return new SerialPortBinder();
    }

    public class SerialPortBinder extends Binder {
        public SerialPortService getService() {
            return SerialPortService.this;
        }
    }

    @Override
    public void onCreate() {
        Log.d("SerialPortService","SerialPortService onCreate");
        super.onCreate();
        time = 10000;
        TIMER = 999;
        // 初始化数据转换工具
        mDataTurn = new DataTurn();
        // 设置广播信息过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction("time");
        filter.addAction("TIMER");
        registerReceiver(setValReceiver, filter);

    }
    private ReadThread readThread;
    private long time;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        readThread = new ReadThread();
        // 打开设备的串口
        openSerialPort();
        // 定时向板子发送指令
        setTimer();
        // 读取返回结果
        readReturnResult();
        flag = true;
        return super.onStartCommand(intent, flags, startId);

    }

    private ScheduledExecutorService executorService;
    private void setTimer(){
        executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(TIMER);
            }
        }, 0, time, TimeUnit.MILLISECONDS);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIMER) {// 向板子写入指令
                writeHexToBoard("553a040396");
            }
        }
    };
    private int TIMER;
    private DataTurn mDataTurn;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private SerialPort mSerialPort;

    private void openSerialPort() {
        try {
            // 串口号: "/dev/ttyWCHUSB2", 波特率: 115200
            mSerialPort = new SerialPort(new File("/dev/ttyWCHUSB2"), 115200, 0);
            PowerApi.mSerialPort = mSerialPort;

            // 获取输入输出流
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();

            new PowerApi().openAllPower();

        } catch (IOException e) {
            Log.d("SerialPortService","找不到该设备文件");
        }
    }

    public void writeHexToBoard(String inHex) {

        Log.d("SerialPortService","writeHexToBoard : " + inHex);

        if (mOutputStream == null)
            return;

        // "553a040396" 为读取电量指令
        byte[] bytes = mDataTurn.HexToByteArr(inHex);

        // 写入数据
        try {
            mOutputStream.write(bytes);
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readReturnResult(){
        // 开启子线程，不断读取返回结果
        readThread.start();
    }

    boolean flag;
    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();

            while (flag) {

                try {
//                    if (mInputStream == null)
//                        return;

                    if (mInputStream.available() <= 0) {
                        continue;
                    } else {
                        Thread.sleep(300);
                    }
                    byte[] buffer = new byte[20];
                    int size = mInputStream.read(buffer);

                    if (size == 7) {
                        byte[] readBytes = new byte[size];
                        System.arraycopy(buffer, 0, readBytes, 0, size);
                        // 将 byte字节数组转换为 int
                        hexToInteger(readBytes);
                    }
                }catch (Exception e){
                    close();
                    openSerialPort();
                    try { Thread.sleep(800); } catch (InterruptedException ex) { }
                }
            }
        }
    }

    private void hexToInteger(byte[] readBytes){

        String hex = mDataTurn.ByteArrToHex(readBytes);
        int hexLength = hex.length();
        Log.d("SerialPortService","hex 数据为 : " + hex + " 长度为: " + hexLength);
        String dataLength = "0604";
        boolean flag = hex.contains(dataLength) && (hexLength >= 8);
        if (flag){
            // 截取电量状态字符串
            String electricString = hex.substring(hexLength - 4, hexLength - 2);
            // 16进制数转化为十进制数
            Integer electricData = Integer.valueOf(electricString,16);

            // 把电量数据写入节点
            writeDataToElectricNode(String.valueOf(electricData));

            // 截取电源状态字符串
            String statusString = hex.substring(hexLength - 6, hexLength - 4);
            String stateIng = "01";
            String stateEd = "00";
            String powerState = "";
            if (stateIng.equals(statusString)){
                powerState = "充电中";
                writeDataToStatusNode("1");
            }else if (stateEd.equals(statusString)){
                writeDataToStatusNode("0");
                powerState = "未充电";
            }

            /*Intent intent = new Intent("power");
            intent.putExtra("powerElectric", String.valueOf(electricData));
            intent.putExtra("powerState", powerState);
            sendBroadcast(intent);*/
        }
    }

    /**电量节点路径*/
    String electricPath = "sys/bus/platform/devices/rk818-battery/cw_capacity";

    private void writeDataToElectricNode(String value) {
        try {
            BufferedWriter bufWriter = new BufferedWriter(new FileWriter(electricPath));
            // 写入数据
            bufWriter.write(value);
            bufWriter.close();
            Log.d("SerialPortService","改写电量节点成功!" + value);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("SerialPortService","改写电量节点失败!");
        }
    }

    /**电源状态节点路径*/
    String statusPath = "sys/bus/platform/devices/rk818-battery/cw_status";

    private void writeDataToStatusNode(String value) {
        try {
            BufferedWriter bufWriter = new BufferedWriter(new FileWriter(statusPath));
            // 写入数据
            bufWriter.write(value);
            bufWriter.close();
            Log.d("SerialPortService","改写电源状态节点成功!" + value);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("SerialPortService","改写电源状态节点失败!");
        }
    }

    private BroadcastReceiver setValReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("TIMER".equals(action)){
                TIMER = intent.getIntExtra("TIMER",999);
                if (TIMER == -999){
                    executorService.shutdownNow();
                    executorService = null;
                }else if (TIMER == 999){
                    if (executorService == null)
                        setTimer();
                }

            }else if ("time".equals(action)){
                time = intent.getLongExtra("time",10000);
                executorService.shutdownNow();
                executorService = null;
                setTimer();
            }
        }
    };
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("SerialPortService","SerialPortService onUnbind");
        return super.onUnbind(intent);
    }


    private void close(){
        if (mInputStream != null) {
            try {
                mInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mOutputStream != null){
            try {
                mOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mSerialPort != null)
            mSerialPort.close();
    }

    @Override
    public void onDestroy() {

        flag = false;
        readThread.interrupt();
        readThread = null;
        close();
        executorService.shutdownNow();

        super.onDestroy();

    }
}
